import xml.etree.ElementTree as ET
import requests
from apiClient import APIClient
import logging
import threading
from lxml import etree
from testrail import *
import time
from parseResult import *
logging.basicConfig(level = logging.INFO, format = 
                    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
from datetime import datetime


################################################################################
## This file used for import robot execution result to test rail
################################################################################
G_PROJECT_ID = 21         # space
G_SUITE_ID = 181        # space
G_INCLUDE_ALL = True
G_MILESTONE_ID = 54514      # Auto TC_Part1
G_ASSIGN_TO_ID = 144     # kenqi
client = APIClient('https://dbschenker.testrail.io/')
client.user = 'ken.qi@dbschenker.com'
client.password = '92godpvJbegbbFVnVO8C-PGtP75T/wyWJ9qkRVPPy'
# AUTO_CASE_RunID = 62425

def get_case_id_by_name(case_name):
    try:
        case = client.send_get(f"get_case/{G_PROJECT_ID}&title={case_name}")
        case_id = case["id"]
        return case_id
    except Exception as e:
        print(f"Error fetching case details: {e}")
        return None

def get_suite_id_by_project():
    try:
        suites = client.send_get(f"get_suites/{G_PROJECT_ID}")
        print(suites)
        return suites
    except Exception as e:
        print(f"Error fetching case details: {e}")
        return None

def get_test_by_id(id):
    try:
        case = client.send_get(f"get_case_fields")
        print(case)
        return case
    except Exception as e:
        print(f"Error fetching case details: {e}")
        return None

def get_all_cases():
    try:
        cases = client.send_get(f"get_cases/{G_PROJECT_ID}&suite_id={G_SUITE_ID}")
        # print(cases)
        return cases
    except Exception as e:
        print(f"Error fetching case details: {e}")
        return None


def get_user_by_email():
    try:
        # Get case details by case name
        users = client.send_get(f"get_user_by_email&email=ken.qi@dbschenker.com")
        print(users)
        return users
    except Exception as e:
        print(f"Error fetching case details: {e}")
        return None

def get_mailstones():
    try:
        # Get case details by case name
        milestones = client.send_get(f"get_milestones/{G_PROJECT_ID}")
        print(milestones)
        return milestones
    except Exception as e:
        print(f"Error fetching case details: {e}")
        return None

def create_test_run(ePROJECT_VERSION):
    #serach test run ,if not exists,create one
    run_name = f"Automation Regression {ePROJECT_VERSION}"    
    all_runs = client.send_get(f"get_runs/{G_PROJECT_ID}")
    all_runs = all_runs['runs']
    index = next((index for index, run in enumerate(all_runs) if run['name'] == run_name), None)
    if index is not None:
       return all_runs[index]['id']
    else:
        run_dict = { 
            'suite_id': G_SUITE_ID, 
            'milestone_id': G_MILESTONE_ID,
            'assignedto_id': G_ASSIGN_TO_ID, 
            'include_all': G_INCLUDE_ALL
        }
        run_dict["name"] = run_name
        url = 'add_run/%s' % G_PROJECT_ID
        response = client.send_post(url, run_dict)
        # logger.info(response)
        return response['id']


'''
Search test run by run name
'''
def search_test_run(run_name):  
    all_runs = client.send_get(f"get_runs/{G_PROJECT_ID}")
    all_runs = all_runs['runs']
    index = next((index for index, run in enumerate(all_runs) if run['name'] == run_name), None)
    if index is not None:
       return all_runs[index]['id']
    else:
        print(f"Test Run of {run_name} not exist !")

'''
Get tests by test run id
'''
def get_tests(run_id):
    url = 'get_tests/%s' % run_id
    return client.send_get(url)

'''
Get single test by test id (id)
'''
def get_singletest(test_id):
    url = 'get_test/%s' % test_id
    return client.send_get(url)    

'''
Update test result and upload screenshot
'''
def add_results(run_id, results,ePROJECT_VERSION):
    tests = get_tests(run_id)
    for test in tests["tests"]:
        for result in results:
            case_id = result['case_id']
            if test['case_id'] == int(case_id):
                elapsedTime = "{}s".format(result['elapsed'])
                add_result_dict = {'status_id': result['status_id'],
                    'comment': 'Updated by automation scripts.',
                    'elapsed':elapsedTime,
                    'version':ePROJECT_VERSION,
                    'assignedto_id':G_ASSIGN_TO_ID,
                    'custom_step_results': result['steps']}             
                url = 'add_result/%s' % test['id']
                response = client.send_post(url, add_result_dict)
                

def test_addResultToTestrun(run_id,ePROJECT_VERSION):
    tests = get_tests(run_id)
    for test in tests["tests"]:
        times=155
        elapsedTime = "{}s".format(times)
        add_result_dict = {'status_id': 2,
                    'comment': 'Updated by automated test scripts.',
                    'custom_comment':'custom comment test',
                    'elapsed':elapsedTime,
                    'version':ePROJECT_VERSION,
                    'assignedto_id':G_ASSIGN_TO_ID}
        url = 'add_result/%s' % test['id']
        response = client.send_post(url, add_result_dict)
        logger.info(response)
                

def import_result_toTestRail(version,output_xml_path):
    ePROJECT_VERSION=version
    RUN_NAME = f"Automation Regression for Release {version} INT"            # TEST RUN name, for which to write result in

    #1.parse output
    parsed_results = parse(output_xml_path)
    # print(parsed_results)

    #2.get run id
    run_id = search_test_run(RUN_NAME)
    # print(run_id)            #for test=54583

    #3.add result
    start = datetime.now()
    add_results(run_id, parsed_results,ePROJECT_VERSION)
    # test_addResultToTestrun(run_id)
    end = datetime.now()
    test_duration = (end - start).total_seconds()
    print(int(test_duration))


def get_case_by_id(case_id):
    if case_id.startswith("C"):
        case_id=case_id[1:]
    try:
        case = client.send_get(f"get_case/{case_id}")
        return case
    except Exception as e:
        print(f"Error fetching case details: {e}")
        return None
    